//
//  UINavigationController+CLExtension.m
//  CLExtension
//
//  Created by CharlieLiao on 2018/1/16.
//  Copyright © 2018年 Charlie. All rights reserved.
//

#import "UINavigationBar+CLExtension.h"
#import <objc/runtime.h>
#import "UIImage+CLDraw.h"

@implementation UINavigationBar (CLExtension)

+ (void)load
{
    if (@available(iOS 11.0, *)) {

    } else {
        //
        Method newImp = class_getInstanceMethod(UINavigationBar.class, @selector(cl_setBarTintColor:));
        Method originImp = class_getInstanceMethod(UINavigationBar.class, @selector(setBarTintColor:));
        method_exchangeImplementations(newImp, originImp);

        //
        newImp = class_getInstanceMethod(UINavigationBar.class, @selector(cl_setBarStyle:));
        originImp = class_getInstanceMethod(UINavigationBar.class, @selector(setBarStyle:));
        method_exchangeImplementations(newImp, originImp);

        //
        newImp = class_getInstanceMethod(UINavigationBar.class, @selector(cl_setShadowImage:));
        originImp = class_getInstanceMethod(UINavigationBar.class, @selector(setShadowImage:));
        method_exchangeImplementations(newImp, originImp);
    }
}

static const char *assoKeyBackgroundImage  = "_akBackgroundImage";

- (void)handlerBackgroundImage {
    @synchronized(self) {
        // 拿到之前的背景图
        id bgImg = objc_getAssociatedObject(self, assoKeyBackgroundImage);
        if (bgImg != NULL && bgImg) {
            // 清空一下之前设置的背景图
            UIImage *barBgImg = [self backgroundImageForBarMetrics:UIBarMetricsDefault];
            if (barBgImg && barBgImg == bgImg) { // 背景图就是上次设置的，进行清空
                [self setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
            }
        }
        
        // 判断现在是否需要设置背景图
        if (self.barStyle == UIBarStyleDefault) {
            if (self.shadowImage && ![self backgroundImageForBarMetrics:UIBarMetricsDefault]) {
                // 开始设置背景图
                UIImage *image = [UIImage graphics:self.barTintColor];
                [self setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
                objc_setAssociatedObject(self, assoKeyBackgroundImage, image, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            }
        }
    }
}

- (void)cl_setBarTintColor:(UIColor *)barTintColor {
    [self cl_setBarTintColor:barTintColor];
    [self handlerBackgroundImage];
}

- (void)cl_setBarStyle:(UIBarStyle)barStyle {
    [self cl_setBarStyle:barStyle];
    [self handlerBackgroundImage];
}

- (void)cl_setShadowImage:(UIImage *)shadowImage {
    [self cl_setShadowImage:shadowImage];
    [self handlerBackgroundImage];
}

- (void)dealloc {
    objc_setAssociatedObject(self, assoKeyBackgroundImage, nil, OBJC_ASSOCIATION_ASSIGN);
    objc_removeAssociatedObjects(self);
}

@end
